package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.atguigu.tingshu.album.mapper.AlbumAttributeValueMapper;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.GuiGuLogin;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.AlbumStat;
import com.atguigu.tingshu.query.album.AlbumInfoQuery;
import com.atguigu.tingshu.vo.album.AlbumAttributeValueVo;
import com.atguigu.tingshu.vo.album.AlbumInfoVo;
import com.atguigu.tingshu.vo.album.AlbumListVo;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class AlbumInfoServiceImpl extends ServiceImpl<AlbumInfoMapper, AlbumInfo> implements AlbumInfoService {

	@Autowired
	private AlbumInfoMapper albumInfoMapper;
	@Autowired
	private AlbumStatMapper albumStatMapper;

	@Autowired
	private AlbumAttributeValueMapper albumAttributeValueMapper;

	@Autowired
	private RabbitService rabbitService;

	/**
	 * 新增专辑
	 * @param albumInfoService
	 * 1.新增 保存
	 * 2.数据源--mysql
	 * 3.涉及的表
	 * album_info
	 * album_attribute_value
	 * album_stat
	 *
	 *
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveAlbumInfo(AlbumInfoVo albumInfoVo) {


		//处理专辑数据
		AlbumInfo albumInfo = BeanUtil.copyProperties(albumInfoVo, AlbumInfo.class);
		//获取用户ID
		Long userId = AuthContextHolder.getUserId();
		albumInfo.setUserId(userId);
		albumInfo.setTracksForFree(5);
		albumInfo.setStatus(SystemConstant.ALBUM_STATUS_PASS);
		//1.保存专辑
		albumInfoMapper.insert(albumInfo);
		//获取专辑ID
		Long albumId = albumInfo.getId();
		//获取专辑属性列表
		List<AlbumAttributeValueVo> albumAttributeValueVoList = albumInfoVo.getAlbumAttributeValueVoList();
		//判断
		if(CollectionUtils.isEmpty(albumAttributeValueVoList)){

			throw new GuiguException(500,"专辑属性不能为空");
		}


		//2.保存专辑属性
		for (AlbumAttributeValueVo albumAttributeValueVo : albumAttributeValueVoList) {
			//创建专辑属性对象
			AlbumAttributeValue albumAttributeValue = BeanUtil.copyProperties(albumAttributeValueVo, AlbumAttributeValue.class);
			albumAttributeValue.setAlbumId(albumId);

			albumAttributeValueMapper.insert(albumAttributeValue);
		}


		//3.初始化专辑统计
		this.initAlbumStat(albumId,SystemConstant.ALBUM_STAT_PLAY);
		this.initAlbumStat(albumId,SystemConstant.ALBUM_STAT_SUBSCRIBE);
		this.initAlbumStat(albumId,SystemConstant.ALBUM_STAT_BUY);
		this.initAlbumStat(albumId,SystemConstant.ALBUM_STAT_COMMENT);


		//判断is_open=1 上架
		if("1".equals(albumInfoVo.getIsOpen())){

			rabbitService.sendMessage(
					MqConst.EXCHANGE_ALBUM,
					MqConst.ROUTING_ALBUM_UPPER,
					albumId
			);

		}



	}

	/**
	 * 查看当前用户专辑分页列表
	 * 1.查询专辑
	 * 2.数据源-mysql
	 * 3.涉及到的表album_info  album_stat
	 * 4.编写sql
	 * 5.选择实现方式 通用mapper xml
	 * @param albumListVoPage
	 * @param query
	 * @return
	 */
	@Override
	public Page<AlbumListVo> findUserAlbumPage(Page<AlbumListVo> albumListVoPage, AlbumInfoQuery query) {


		return albumInfoMapper.selectUserAlbumPage(albumListVoPage,query);
	}

	/**
	 *  根据ID删除专辑
	 * @param id
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void removeAlbumInfo(Long id) {

		//查询专辑
		AlbumInfo albumInfo = albumInfoMapper.selectById(id);
		//获取当前声音包含总数
		Integer includeTrackCount = albumInfo.getIncludeTrackCount();
		//判断
		if(includeTrackCount>0){

			throw new GuiguException(500,"请先删除当前专辑的声音！");
		}

		//删除专辑信息
		albumInfoMapper.deleteById(id);
		//删除专辑属性信息
		 //delete from album_attribute_value where album_id=?
		//构建条件对象
		QueryWrapper<AlbumAttributeValue> attributeValueQueryWrapper = new QueryWrapper<>();
		attributeValueQueryWrapper.eq("album_id",id);

		albumAttributeValueMapper.delete(attributeValueQueryWrapper);

		//删除专辑统计信息

		QueryWrapper<AlbumStat> albumStatQueryWrapper = new QueryWrapper<>();
		albumStatQueryWrapper.eq("album_id",id);

		albumStatMapper.delete(albumStatQueryWrapper);


		//下架接口
		rabbitService.sendMessage(
				MqConst.EXCHANGE_ALBUM,
				MqConst.ROUTING_ALBUM_LOWER,
				id
		);




	}

	/**
	 * 根据ID查询专辑信息
	 * @param id
	 * @return
	 */
	@Override
	@GuiGuLogin(required = true)
	public AlbumInfo getAlbumInfo(Long id) {

		//先查询专辑
		AlbumInfo albumInfo = albumInfoMapper.selectById(id);

		//查询专辑属性
		//select*from album_attribute_value where album_id=?
		//构建查询对象
		QueryWrapper<AlbumAttributeValue> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("album_id",id);
		//查询
		List<AlbumAttributeValue> attributeValueList = albumAttributeValueMapper.selectList(queryWrapper);
		//封装
		if(albumInfo!=null){

			albumInfo.setAlbumAttributeValueVoList(attributeValueList);
		}


		return albumInfo;
	}

	/**
	 *  修改专辑
	 * @param id
	 * @param albumInfoVo
	 *
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateAlbumInfo(Long id, AlbumInfoVo albumInfoVo) {

		//获取原来is_open的旧值
		String isOpen = albumInfoMapper.selectById(id).getIsOpen();


		//拷贝并生成对象
		AlbumInfo albumInfo = BeanUtil.copyProperties(albumInfoVo, AlbumInfo.class);
		//设置id
		albumInfo.setId(id);
		//修改专辑
		albumInfoMapper.updateById(albumInfo);

		//修改专辑属性---修改多的一方，因为不好确定某一个具体的值是否更改，所以先删除，在添加

		// where album_id=1612
		//构建条件对象
		QueryWrapper<AlbumAttributeValue> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("album_id",id);
		//删除
		albumAttributeValueMapper.delete(queryWrapper);

		//保存最新属性
		//获取专辑属性列表
		List<AlbumAttributeValueVo> albumAttributeValueVoList = albumInfoVo.getAlbumAttributeValueVoList();
		//判断
		if(CollectionUtils.isEmpty(albumAttributeValueVoList)){

			throw new GuiguException(500,"专辑属性不能为空");
		}


		//2.保存专辑属性
		for (AlbumAttributeValueVo albumAttributeValueVo : albumAttributeValueVoList) {
			//创建专辑属性对象
			AlbumAttributeValue albumAttributeValue = BeanUtil.copyProperties(albumAttributeValueVo, AlbumAttributeValue.class);
			albumAttributeValue.setAlbumId(id);

			albumAttributeValueMapper.insert(albumAttributeValue);
		}


		//判断修改后is_open的状态

		if("1".equals(albumInfoVo.getIsOpen())){
			//上架接口
			rabbitService.sendMessage(
					MqConst.EXCHANGE_ALBUM,
					MqConst.ROUTING_ALBUM_UPPER,
					id
			);


		}

		if("0".equals(albumInfoVo.getIsOpen())&&!"0".equals(isOpen)){

			//下架
			rabbitService.sendMessage(
					MqConst.EXCHANGE_ALBUM,
					MqConst.ROUTING_ALBUM_LOWER,
					id
			);

		}



	}

	/**
	 * 获取当前用户全部专辑列表
	 * @param userId
	 * @return
	 */
	@Override
	public List<AlbumInfo> findUserAllAlbumList(Long userId) {

		//语句： select id,album_stitle,status from album_info where userid=?  order by update_tie desc

		//构建查询对象
		QueryWrapper<AlbumInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id",userId);
		queryWrapper.orderByDesc("update_time");
		queryWrapper.select("id","album_title","status");

		//过滤数据条数
		queryWrapper.last(" limit  100 ");
		//执行查询
		List<AlbumInfo> albumInfoList = albumInfoMapper.selectList(queryWrapper);
		return albumInfoList;
	}

	/**
	 * 根据专辑ID获取专辑统计信息
	 * @param albumId
	 * @return
	 */
	@Override
	public AlbumStatVo getAlbumStatVo(Long albumId) {


		return albumInfoMapper.selectAlbumStatVoById(albumId);
	}



	/**
	 * 专辑统计初始化
	 * @param albumId
	 * @param statType
	 */
	public void initAlbumStat(Long albumId,String statType){

		//创建专辑统计实体
		AlbumStat albumStat = new AlbumStat();
		albumStat.setAlbumId(albumId);
		albumStat.setStatType(statType);
		albumStat.setStatNum(0);

		//保存初始统计
		albumStatMapper.insert(albumStat);


	}


}
